import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "./store";
import { getRequest } from "../util/Auth";
import { NulResponse, createEmptyRequest, createRequest } from "./common";
import { removeElementFromArray } from "../util/Arrays";

type IssueInvoiceType = 'retail' | 'wholesale';
type IssueInvoiceStatus = 'approved' | 'rejected' | 'audit';

interface SalesManagementEntry {
  id: string;
  date: string;
  issuedBy: string;
  type: IssueInvoiceType;
  totalAmount: number;
  grossProfit: number;
  status: IssueInvoiceStatus;
}

interface SalesManagementState {
  fetched: boolean;
  entries: SalesManagementEntry[];
}

interface DeleteInvoiceRequest {
  id: string;
}

const salesManagementInitialState: SalesManagementState = {
  fetched: false,
  entries: []
};

export const fetchAllSalesInvoice = createAsyncThunk('api/fetchAllInvoice', async (_: void, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<SalesManagementEntry[]>>('/service/invoice/fetchAll',
      createEmptyRequest());
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

export const deleteSalesInvoice = createAsyncThunk('api/deleteInvoice', async (deleteRequest: DeleteInvoiceRequest, { getState, rejectWithValue }) => {
  const state = getState() as RootState;
  try {
    const request = getRequest(state);
    const response = await request.post<NulResponse<null>>('/service/invoice/deleteEntry', createRequest(deleteRequest));
    return response.data;
  }
  catch (e) {
    return rejectWithValue(e);
  }
});

const salesManagementSlice = createSlice({
  name: 'sales',
  initialState: salesManagementInitialState,
  reducers: {

  },
  extraReducers: (builder) => {
    builder.addCase(deleteSalesInvoice.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(deleteSalesInvoice.fulfilled, (state, action) => {
      const id: string = action.meta.arg.id;
      const index: number = state.entries.findIndex((value) => value.id === id);
      if (index !== -1) {
        state.entries = removeElementFromArray(state.entries, index);
      }
    }).addCase(fetchAllSalesInvoice.rejected, (state, action) => {
      console.error(action.error);
    }).addCase(fetchAllSalesInvoice.fulfilled, (state, action) => {
      state.fetched = true;
      state.entries = action.payload.result;
    });
  }
});

export type { SalesManagementEntry };
export const selectSalesFetched = (state: RootState) => state.salesManagementReducer.fetched;
export const selectSalesEntries = (state: RootState) => state.salesManagementReducer.entries;
export default salesManagementSlice.reducer;
